﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public abstract class UIBaseTab : MonoBehaviour
{
    /// <summary>
    /// Tab 标签切换事件，请处理标签的切换状态
    /// </summary>
    [System.Serializable]
    public class TabChangeEvent : UnityEvent<int> { };


    /// <summary>
    /// 标签更新事件，用于在切换时，更新标签的结果
    /// </summary>
    [System.Serializable]
    public class TabUpdateEvent : UnityEvent<GameObject, bool> { };

    //标签切换回调函数，标签切换时使用，控制一个
    public TabChangeEvent onTabChange;

    public int curIndex = 0;


    public virtual void Init()
    {
        //初始化刷新选择的标签
        this._UpdateTab(this.curIndex);

        //更新绑定事件
        this.UpdateBindEvent();
    }

    protected void UpdateBindEvent()
    {
        int index = 0;
        foreach (Transform item in this.transform)
        {
            var button = item.GetComponent<Button>();
            if (button == null) button = item.gameObject.AddComponent<Button>();
            button.onClick.RemoveAllListeners();
            button.onClick.AddListener(() => _OnButtonDown(button.transform.GetSiblingIndex()));
            index++;
        }
    }

    /// <summary>
    /// 按钮按下
    /// </summary>
    /// <param name="index"></param>
    private void _OnButtonDown(int index)
    {
        index = Mathf.Clamp(index, 0, this.transform.childCount);

        if (curIndex != index)
        {
            curIndex = index;
            //标签页的切换
            onTabChange.Invoke(index);
            this._UpdateTab(index);
            this.OnButtonDown(index);
        }
    }

    /// <summary>
    /// 切换标签页
    /// </summary>
    /// <param name="index"></param>
    public void ToggleTab(int index)
    {
        this._OnButtonDown(index);
    }

    public void NextTab()
    {
        this.curIndex++;
        this.ToggleTab(this.curIndex);
    }

    public void BackTab()
    {
        this.curIndex--;
        this.ToggleTab(this.curIndex);
    }

    /// <summary>
    /// 强制刷新tab的显示,只刷新显示部分
    /// </summary>
    /// <param name="index"></param>
    public void ForceUpdateDisplay(int index)
    {
        this._UpdateTab(index);
    }

    // Update is called once per frame
    private void _UpdateTab(int index)
    {
        //更新所有标签的状态
        foreach (Transform item in this.transform)
        {
            if (index == item.GetSiblingIndex())
            {
                UpdateTabState(item.gameObject, true);
            }
            else
            {
                UpdateTabState(item.gameObject, false);
            }

        }
    }

    protected abstract void UpdateTabState(GameObject obj, bool isSelected);

    public virtual void OnButtonDown(int index)
    {

    }



}
